<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form
          ref="formRef"
          class="antd-modal-form"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          name="GbtIntegralVoteForm"
        >
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="期数"
                v-bind="validateInfos.period"
                id="GbtIntegralVoteForm-period"
                name="period"
              >
                <a-input v-model:value="formData.period" placeholder="请输入期数" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="名称"
                v-bind="validateInfos.name"
                id="GbtIntegralVoteForm-name"
                name="name"
              >
                <JSearchSelect
                  v-model:value="formData.name"
                  placeholder="请输入名字"
                  dict="gbt_integral_user,name,id"
                  async
                  allow-clear
                  @change="onUserChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="用户id"
                v-bind="validateInfos.userid"
                id="GbtIntegralVoteForm-userid"
                name="userid"
              >
                <a-input v-model:value="formData.userid" placeholder="请输入用户id" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="一级部门"
                v-bind="validateInfos.firstDept"
                id="GbtIntegralVoteForm-firstDept"
                name="firstDept"
              >
                <a-input v-model:value="formData.firstDept" placeholder="请输入一级部门" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="二级部门"
                v-bind="validateInfos.secondDept"
                id="GbtIntegralVoteForm-secondDept"
                name="secondDept"
              >
                <a-input v-model:value="formData.secondDept" placeholder="请输入二级部门" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="岗位"
                v-bind="validateInfos.title"
                id="GbtIntegralVoteForm-title"
                name="title"
              >
                <a-input v-model:value="formData.title" placeholder="请输入岗位" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="评选类型"
                v-bind="validateInfos.voteType"
                id="GbtIntegralVoteForm-voteType"
                name="voteType"
              >
                <a-select v-model:value="formData.voteType" placeholder="请选择评选类型" allow-clear>
                  <a-select-option value="奋斗之星">奋斗之星</a-select-option>
                  <a-select-option value="效率之星">效率之星</a-select-option>
                  <a-select-option value="创新之星">创新之星</a-select-option>
                  <a-select-option value="学习之星">学习之星</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="理由"
                v-bind="validateInfos.reason"
                id="GbtIntegralVoteForm-reason"
                name="reason"
              >
                <j-editor v-model:value="formData.reason" :autoFocus="false" />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="24">
              <a-form-item
                label="票数"
                v-bind="validateInfos.votes"
                id="GbtIntegralVoteForm-votes"
                name="votes"
              >
                <a-input-number
                  v-model:value="formData.votes"
                  placeholder="请输入票数"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="普通投票"
                v-bind="validateInfos.normalVote"
                id="GbtIntegralVoteForm-normalVote"
                name="normalVote"
              >
                <a-input-number
                  v-model:value="formData.normalVote"
                  placeholder="请输入普通投票"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="委员会投票"
                v-bind="validateInfos.vipVote"
                id="GbtIntegralVoteForm-vipVote"
                name="vipVote"
              >
                <a-input-number
                  v-model:value="formData.vipVote"
                  placeholder="请输入委员会投票"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col> -->
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../GbtIntegralVote.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { getUser } from '../../integralRecord/GbtIntegralRecord.api';
import { JSearchSelect } from '/@/components/Form';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  name: '',
  userid: '',
  firstDept: '',
  secondDept: '',
  title: '',
  voteType: '',
  reason: '',
  votes: undefined,
  normalVote: undefined,
  vipVote: undefined,
  period: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  name: [{ required: true, message: '请输入名称!' }],
  period: [{ required: true, message: '请输入期数!' }],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

// 选中用户时触发，可以同步其他表单字段，比如部门
const onUserChange = (userid, option) => {
  // option.extra 就是完整用户数据
  getUser({ id: userid })
    .then((user) => {
      formData.name = user.name;
      formData.userid = user.userid;
      formData.firstDept = user.firstDept;
      formData.secondDept = user.secondDept;
      formData.title = user.title;
    })
    .catch((err) => {
      console.error('获取用户详情失败', err);
    });
};

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key];
      }
    });
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
